<template>
  <div id="app">
    <!-- <div class="title d_h_col">
      {{ $t("home.pleaseNote") }}
    </div> -->
    <div class="inputButton">
      <el-form ref="chapterTitle" :rules="rules" :model="chapterMess">
        <el-form-item prop="title">
          <el-input
            v-model="chapterMess.title"
            :placeholder="$t('home.enterSectionName')"
            :disabled="titleBtrue"
            @blur="titleBlur"
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="con_title">
        <el-button
          class="deleteDaf"
          v-if="draftOrSend == '0'"
          type="danger"
          size="mini"
          @click="deleteDaf"
          >{{ $t("home.delete") }}</el-button
        >
        <div class="control" v-if="buttonTrue == 1 ? false : true">
          <el-button
            v-if="!titleBtrue"
            type="primary"
            size="mini"
            @click="savebook"
            >
            <div style="margin-left:-12px">
              {{ $t("home.preservation") }}
            </div>
            </el-button
          >
          <el-button
            v-if="!titleBtrue"
            :disabled="
              regContent.length >= 500 && chapterMess.title != '' ? false : true
            "
            type="primary"
            size="mini"
            @click="releaseArticle"
          >
            {{ $t("home.release") }}
          </el-button>
          <el-button
            type="primary"
            size="mini"
            v-if="titleBtrue"
            @click="modify"
          >
            {{ $t("home.revise") }}
          </el-button>
        </div>
      </div>
    </div>
    <div class="content">
      <div class="contentText">
        <editor
          class="editor"
          ref="editorOne"
          v-model="regContent"
          @change="changeDetail"
        >
        </editor>
        <p>{{ fontNum.length }}/5000</p>
      </div>
    </div>
    <el-dialog
      :title="$t('home.confirmSectionInformation')"
      style="z-index: 20000"
      :visible.sync="articleVisible"
    >
      <div class="dialogStyle">
        <div>
          {{ $t("home.publishedChapters") }}:<span>{{
            chapterMess.title
          }}</span>
        </div>
        <div>
          {{ $t("home.chapterWords") }}:<span>{{ fontNum.length }}</span>
        </div>
        <div>
          {{ $t("home.booksName") }}:<span>{{
            this.sessGetData.bookTitle
          }}</span>
        </div>
        <div>{{ $t("home.latestChapter") }}:<span></span>{{ newTitle }}</div>
        <!-- <div class="radioCelect">
          <div>发布时间:</div>
          <div>
            <el-radio v-model="radio" label="0">立即</el-radio>
            <el-radio v-model="radio" label="1">定时</el-radio>
          </div>
        </div> -->
        <div v-if="radio == '1' ? true : false">
          <el-date-picker
            v-model="dataTime"
            type="datetime"
            :placeholder="$t('home.selectDateAndTime')"
            align="right"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
        </div>
      </div>
      <span slot="footer">
        <el-button @click="articleVisible = false">{{
          $t("home.cancel")
        }}</el-button>
        <el-button type="primary" @click="submitRelease">{{
          $t("home.confirm")
        }}</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :title="$t('home.containsSensitive')"
      style="z-index: 20000"
      :visible.sync="worldRreg"
    >
      <div ref="worldContent" v-html="worldText"></div>
    </el-dialog>
  </div>
</template>

<script>
import Editor from "@/components/wangEditor";
import {
  addChapterDraft,
  addChapterCheck,
  updateChapterDraft,
  selectLatestChapter,
  deleteChapterDraft,
  dangerousWord,
} from "@/api/authorCenter/createBook";
export default {
  name: "",
  components: {
    // quillEditor,
    Editor,
  },
  props: ["chapterMess", "titleBtrue", "buttonTrue", "FnEvent", "draftOrSend"],

  data() {
    return {
      bTitle: false,
      worldRreg: false,
      worldText: "",
      wordRegArry: [], //敏感词
      sessGetData: {},
      fontNum: "",
      regContent: "", //章节内容
      list: [],
      dataTime: "",
      newTitle: "", //最新章节
      radio: "",
      pickerOptions: {
        //日期
        shortcuts: [
          {
            text: this.$t("home.today"),
            onClick(picker) {
              picker.$emit("pick", new Date());
            },
          },
          {
            text: this.$t("home.yesterday"),
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: this.$t("home.aWeekAgo"),
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
        ],
      },
      rules: {
        title: [
          {
            required: true,
            message: this.$t("home.enterSectionName"),
            trigger: "blur",
          },
          {
            max: 20,
            message: this.$t("home.enterLess20Title"),
            trigger: "blur",
          },
        ],
      },
      articleVisible: false, //发布章节信息弹层
      message: {},
      chapterTitle: "", //章节名称
      book_value: "",
      book_value_hml: "",
      modifyOrCreat: 0, // 1：修改草稿章节保存草稿箱  0：新建章节保存草稿箱
      type: false,
      book: {
        type: 1,
        name: this.$t("home.biographyOfMortalCultivation"),
        content: this.$t("home.test"),
      },
      avv: false,
      content: this.$t("home.test"),
      editorOption: {},
    };
  },
  watch: {
    chapterMess(val, oldVal) {
      //监听格式化章节内容
      if (!this.chapterMess) {
        this.chapterMess = {
          bookId: "",
          title: "",
          // contentId: "",
          content: "",
          contentType: 0,
          wordsCount: "",
        };
        this.titleBtrue = false;
      }
      if (this.chapterMess.content == "") {
        // this.chapterMess.content = this.regContent;
        this.regContent = "";
        this.chapterMess.checkBookId = this.sessGetData.bookId;
        this.chapterMess.wordsCount = this.regContent.length;
      } else {
        // let regItem = JSON.parse(this.chapterMess.content).list;
        this.regContent = this.chapterMess.content;
        // let myArry = [];
        // regItem.forEach((ele) => {
        //   ele.text + "</p>";
        //   myArry.push("<p>" + ele.text + "</p>");
        // });
        // this.regContent = myArry.join("");
      }
    },
  },

  methods: {
    //String转义
    escapeHTML(a){
        a = "" + a;
        return a.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
    },
    //String 反转义
    unescapeHTML(a){
        a = "" + a;
        return a.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&").replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&nbsp;/g," ").replace(/<br>|<br\/>/g,"\n")
    },
    //文章标题
    titleBlur(a) {
      if (this.chapterMess.title == "") {
        this.bTitle = false;
      } else {
        this.bTitle = true;
      }
    },
    //删除草稿
    deleteDaf() {
      let that = this;
      let params = {
        bookId: this.chapterMess.checkBookId,
        draftId: this.chapterMess.id,
      };
      this.$confirm(that.$t("home.deleNotRestore"), {
        confirmButtonText: that.$t("home.confirm"),
        cancelButtonText: that.$t("home.cancel"),
        type: "warning",
      })
        .then(() => {
          deleteChapterDraft(params).then((res) => {
            if ((res.code = 1)) {
              that.$emit("refreshFn");
              let data = {
                bookId: "",
                content: "",
                contentType: 0,
                id: "",
                title: "",
                wordsCount: "",
              };
              that.chapterMess = data;
              that.titleBtrue = false;
              that.$refs["editorOne"].end();
              that.draftOrSend = "1";
            }
          });
        })
        .catch(() => {});
    },
    test() {
      this.$refs.writeCont.innerHTML.replace(/&nbsp/g, "");
    },
    handleOpen(key, keyPath) {},
    handleClose(key, keyPath) {},
    check() {},
    // 转成安卓端相同的编译形式
    toAndroid(arv) {
      var arc = arv.replace(
        /<p>(([\s\S])*?)<\/p>/g,
        '{"blockType":"block_normal_text","inlineStyleEntities":[],"text":"$1"},'
      );
      return arc;
    },
    control() {
      this.toAndroid(this.book.detail);
    },
    // 动态修改差异
    changeDetail() {
      this.fontNum = this.regContent.replace(/<\/?.+?>/g, "");
      let patrn = /[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/g;
      this.fontNum = this.fontNum.replace(patrn, " ");
      let r = /\s+/;
      this.fontNum = this.fontNum.split(r);
      // this.fontNum = this.fontNum.replace(/[&nbsp;]|[]/g, "");
    },
    // 保存到草稿箱
    savebook() {
      let that = this;
      this.$refs["chapterTitle"].validate((valid) => {
        if (valid) {
          //格式化数据
          let newData = this.regContent.replace(/<p>/g, "");
          let myArry = newData.split("</p>");

          this.list = [];
          myArry.forEach((element) => {
            // let ietem = {
            //   blockType: "block_normal_text",
            //   inlineStyleEntities: [],
            //   text: "",
            // };
            // ietem.text = element.replace(/[&nbsp;]|[]/g, "");
            if (element) {
              if(element === "<br>" || element === "<br/>") {
                this.list.push("\n");
              } else {
                this.list.push(element + "\n");
              }
            }
          });
          let newContent = this.unescapeHTML(this.list.join(""));
          // let newContent = { list: this.list };
          if (this.draftOrSend == "0") {
            //判断是走新建 草稿 还是修改草稿接口
            //修改草稿保存
            let params = {
              checkBookId: this.chapterMess.checkBookId,
              content: newContent,
              contentType: this.chapterMess.contentType,
              id: this.chapterMess.id,
              //  checkContentId:this.chapterMess.id,
              wordsCount: this.fontNum.length, //this.chapterMess.wordsCount,
              title: this.chapterMess.title,
            };
            // this.chapterMess.content = JSON.stringify(newContent);
            updateChapterDraft(params).then((res) => {
              if (res.code == 1) {
                let data = {
                  bookId: "",
                  content: "",
                  contentType: 0,
                  // checkContentId:true,
                  id: "",
                  title: "",
                  wordsCount: "",
                };
                this.chapterMess = data;
                this.$message({
                  type: "success",
                  message: that.$t("home.saveSuccessfully"),
                });
              }
              this.$emit("refreshFn"); //刷新列表
            });
          } else {
            //新建  修改已发章节 保存id
            let params = {
              checkBookId: this.sessGetData.bookId,
              title: this.chapterMess.title,
              checkContentId:
                this.chapterMess.checkContentId == true
                  ? ""
                  : this.chapterMess.id, //章节Id
              content: newContent,
              contentType: 0,
              // wordsCount: this.chapterMess.content.length,
              wordsCount: this.fontNum.length,
            };
            addChapterDraft(params).then((res) => {
              if (res.code == 1) {
                let data = {
                  bookId: "",
                  content: "",
                  contentType: 0,
                  // checkContentId:true,
                  id: "",
                  title: "",
                  wordsCount: "",
                };
                this.chapterMess = data;
                this.$message({
                  type: "success",
                  message: that.$t("home.savedToDraftBox"),
                });
                this.$emit("refreshFn"); //刷新列表
              }
            });
          }
        }
      });
    },
    // 发布切换为不可编辑
    releaseArticle() {
      this.$refs["chapterTitle"].validate((valid) => {
        if (valid) {
          let newData = this.regContent.replace(/<p>/g, "");
          for (let i = 0; i < this.wordRegArry.length; i++) {
            newData = newData.replace(
              new RegExp(this.wordRegArry[i], "g"),
              '<font style="color:red"> ' + this.wordRegArry[i] + "</font>"
            );
            if (newData.indexOf(this.wordRegArry[i]) != -1) {
              this.worldRreg = true;
            }
            this.worldText = newData;
          }
          this.articleVisible = !this.worldRreg;

          // this.$refs["editorOne"].start();
          //获取发布最新章节
          let oparams = {
            bookId: this.chapterMess.checkBookId,
            draftId: this.chapterMess.id,
          };
          console.log(oparams, "dfdsfsdfdsfsdffsd");
          selectLatestChapter(oparams).then((res) => {
            this.newTitle = res.source.title;
          });
        }
      });
    },
    toBookDraftChapter() {
      //跳转道最新章节已发布内容
      let params = {
        bookId: JSON.parse(sessionStorage.getItem("writeArticle")).bookId,
      };
      // sessionStorage.removeItem("writeArticle");
      // sessionStorage.setItem("writeArticle", JSON.stringify(item));
      selectLatestChapter(params).then((res) => {
        if (res.code == 1) {
          this.$router.push({
            path: "/writerTool",
            query: { contenId: res.source.id, state: res.source.state },
          });
        }
      });
    },
    //确认发布
    submitRelease() {
      let newData = this.regContent.replace(/<p>/g, "");

      let myArry = newData.split("</p>");

      this.list = [];
      myArry.forEach((element) => {
        // let ietem = {
        //   blockType: "block_normal_text",
        //   inlineStyleEntities: [],
        //   text: "",
        // };
        // ietem.text = element.replace(/[&nbsp;]|[]/g, "");
        if (element) {
              if(element === "<br>" || element === "<br/>") {
                this.list.push("\n");
              } else {
                this.list.push(element + "\n");
              }
            }
      });
      // let newContent = { list: this.list };
      let newContent = this.unescapeHTML(this.list.join(""));
      let params = {
        checkBookId: this.chapterMess.checkBookId,
        content: (this.chapterMess.content = newContent),
        contentType: 0,
        draftId: this.chapterMess.id,
        title: this.chapterMess.title,
        wordsCount: this.fontNum.length,
      };
      if (this.draftOrSend == "0") {
        //点击草稿章节
        // 草稿文章
        if (this.chapterMess.checkContentId) {
          //是已发章节保存进来的草稿 有checkContentId
          let item = { checkContentId: this.chapterMess.checkContentId };
          Object.assign(params, item);
          console.log(params, "params");
        } else {
          //草稿章节 无checkContentId
          let item = { draftId: this.chapterMess.id };
          Object.assign(params, item);
        }
      } else {
        //点击已发章节
        let item = { checkContentId: this.chapterMess.id };
        Object.assign(params, item);
      }
      addChapterCheck(params).then((res) => {
        //发布
        if (res.code == 1) {
          this.articleVisible = false;
          // this.toBookDraftChapter()
          // 发布成功切换为浏览状态
          let data = {
            bookId: "",
            content: "",
            contentType: 0,
            id: "",
            title: "",
            wordsCount: "",
          };
          this.chapterMess = data;
          this.$emit("refreshFn"); //刷新列表
        }
      });
    },
    // 切换为可编辑内容
    modify() {
      this.modifyOrCreat = 1;
      sessionStorage.setItem("modify", "true");
      this.$refs["editorOne"].end();
      this.titleBtrue = false;
    },
  },

  mounted() {
    this.sessGetData = JSON.parse(sessionStorage.getItem("writeArticle"));
    this.$emit("getEditer", this.$refs["editorOne"]); //传给列表栏目 编辑器对象
    this.book.name = this.sessGetData.bookTitle; //默认加载书名
    dangerousWord().then((res) => {
      this.wordRegArry = res.source;
    });
  },
};
</script>

<style scoped="scoped" lang="scss">
::v-deep .el-button {
  height: 48px;
  font-size: 18px;
  width: 90px;
  border-radius: 8px;
}
::v-deep .el-input__inner {
  height: 48px;
  border-radius: 8px;
  font-size: 18px;
}
.el-form-item {
  margin: 20px 0;
  padding-left: 20px;
}
.el-form {
  flex: 1;
}
.inputButton {
  display: flex;
  align-items: center;
}
.deleteDaf {
  margin-right: 10px;
}
.contentText {
  position: relative;
  .editor{
    white-space: pre-wrap;
  }
  p {
    position: absolute;
    bottom: 15px;
    right: 15px;
    z-index: 100;
  }
}
.radioCelect {
  display: flex;
  div {
    margin-right: 20px;
  }
}
.dialogStyle {
  width: 50%;
  margin-left: 25%;
  line-height: 45px;
  span {
    margin-left: 15px;
  }
}
::v-deep .ql-container {
  height: 500px;
  overflow-y: auto;
}
#app {
  background: #fff;
  overflow-y: none;
  margin-left: 20px;
  padding-bottom: 20px;
  .editorStyle {
    width: 98%;
    margin-top: 20px;
  }
  .title {
    height: 40px;
    background: #fff0f1;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #cd001a;
    width: 100%;
    text-align: center;
  }

  .con_title {
    box-sizing: border-box;
    display: flex;
    flex-direction: row;
    justify-content: flex-end;
    padding: 20px;
  }

  .content {
    box-sizing: border-box;
    padding: 0 20px;
    .name {
      p {
        width: 221px;
        height: 25px;
        font-size: 18px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #333333;
        line-height: 25px;
        margin: 10px 0;
      }

      input {
        border: none;
        font-size: 18px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        // color: #CCCCCC;
        line-height: 25px;
        outline: none;
        margin: 10px 0;
      }
    }
  }
}
</style>
